import fetch from 'dva/fetch'
import { notification } from 'antd'

function checkstatus (response) {
    if (response.status >= 200 && response.status < 300) {
      return response
    }
    notification.error({
        message: `请求错误 ${response.status}: ${response.url}`,
        description: response.statusText,
      })
    const error = new Error(response.statusText)
    error.response = response
    throw error
}

export default function request (url, options) {
    const defaultOptions = {
        credentials: 'include',
      }
    const newOptions = { ...defaultOptions, ...options }
    if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
        newOptions.header = {
            Accept: 'application/json',
            'Content-Type': 'application/json; charset=utf-8',
            ...newOptions.header,
        }
        newOptions.body = JSON.stringify(newOptions.body)
    }

    return fetch(url, newOptions)
        .then(checkstatus)
        .then(response => response.json())
        .catch((error) => {
            if (error.code) {
                notification.error({
                    message: error.name,
                    description: error.messae,
                })
            }
            if ('stack' in error && 'message' in error) {
                notification.error({
                    message: `请求错误: ${url}`,
                    description: error.message,
                  })
            }
            return error
        })
}
